﻿using System;
using System.Net.WebSockets;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace client
{
    public class WebSocketClient
    {
        private readonly string _uri;

        private ClientWebSocket _webSocket;

        public WebSocketClient(string uri)
        {
            _uri = uri;
        }

        /// <summary>
        /// 连接
        /// </summary>
        /// <returns></returns>
        public async Task ConnectAsync()
        {
            _webSocket = new ClientWebSocket();
            await _webSocket.ConnectAsync(new Uri(_uri), CancellationToken.None);
            Console.WriteLine("Connected!");
            await ReceiveMessages();
        }

        /// <summary>
        /// 收消息
        /// </summary>
        /// <returns></returns>
        private async Task ReceiveMessages()
        {
            var buffer = new byte[1024 * 4];
            while (_webSocket.State == WebSocketState.Open)
            {
                WebSocketReceiveResult result;
                var segment = new ArraySegment<byte>(buffer);
                do
                {
                    result = await _webSocket.ReceiveAsync(segment, CancellationToken.None);
                    try
                    {
                        string msg = System.Text.Encoding.UTF8.GetString(buffer, 0, result.Count);
                        Console.WriteLine("Received: " + msg);
                        this.OnMessage?.Invoke(this, new MessageEventArgs<String>(msg));//产生收到消息事件
                    }
                    catch (Exception ex) 
                    {
                    
                    }
                }
                while (!result.EndOfMessage);
            }
        }

        /// <summary>
        /// 发消息
        /// </summary>
        /// <param name="message"></param>
        /// <returns></returns>
        public async Task SendMessageAsync(string message)
        {
            if (_webSocket.State == WebSocketState.Open)
            {
                var buffer = System.Text.Encoding.UTF8.GetBytes(message);
                var segment = new ArraySegment<byte>(buffer);
                await _webSocket.SendAsync(segment, WebSocketMessageType.Text, true, CancellationToken.None);
            }
        }

        /// <summary>
        /// 关闭连接
        /// </summary>
        /// <returns></returns>
        public async Task CloseAsync()
        {
            if (_webSocket.State == WebSocketState.Open)
            {
                await _webSocket.CloseAsync(WebSocketCloseStatus.NormalClosure, "Closing", CancellationToken.None);
            }
        }

        public event EventHandler<MessageEventArgs<String>> OnMessage;

        public class MessageEventArgs<T> : EventArgs where T : class
        {
            /// <summary>
            /// 消息
            /// </summary>
            public T Message { get; set; }


            public MessageEventArgs()
            {

            }

            public MessageEventArgs(T data)
            {
                this.Message = data;
            }
        }

    }
}
